//
//  XDTools.m
//  HengHuaSupervision
//
//  Created by XD-XY on 3/20/14.
//  Copyright (c) 2014 XD-XY. All rights reserved.
//

#import "XDTools.h"
#import "Reachability.h"
#import "FMDatabase.h"
#import <Security/Security.h>
#import "XDHeader.h"
#import "MainViewController.h"

@implementation XDTools
DEFINE_SINGLETON_FOR_CLASS(XDTools)

+(XDNavigationController *)getAppNavigationControllerPointer:(UINavigationController *)navigationController
{
    XDNavigationController * nav = (XDNavigationController *)navigationController;
    return nav;
}

+(BOOL)NetworkReachable
{
    NetworkStatus wifi = [[Reachability reachabilityForLocalWiFi] currentReachabilityStatus];
    NetworkStatus gprs = [[Reachability reachabilityForInternetConnection] currentReachabilityStatus];
    if(wifi == NotReachable && gprs == NotReachable)
    {
        return NO;
    }
    return YES;
}

+ (NSDictionary *)JSonFromString:(NSString* )result
{
    NSDictionary *json = [result objectFromJSONStringWithParseOptions:JKParseOptionLooseUnicode];
    return json;
    
}

+(UIImage *)stretchableImag:(UIImage *)image
{
    //image = [image stretchableImageWithLeftCapWidth:2 topCapHeight:10];
    //上左下右
    //image = [UIImage imageNamed:@"homepage_cellodd_img"];
    image = [image resizableImageWithCapInsets:UIEdgeInsetsMake(10,2,10,2)];
    return image;
}

+ (AppDelegate *)appDelegate
{
    return (AppDelegate *)[[UIApplication sharedApplication] delegate];
}


/***
 **自适应高度和宽度，其中参数widget是你要改变的label,size是定义label的长宽最大值,sizefont这个是字体的大小
 ***/
+(CGRect )xyAutoSizeOfWidget:(UILabel *)widget andSize:(CGSize)size andtextFont:(CGFloat )sizefont
{
    widget.numberOfLines = 0;
    CGRect rect = widget.frame;
    if ([widget.text length]==0){
        return CGRectMake(rect.origin.x, rect.origin.y, 0, 0);
    }
   // NSLog(@"rect = %f %f %f %f",rect.origin.x,rect.origin.y,rect.size.width,rect.size.height);
    if (IOS7){
        NSDictionary * tdic = [NSDictionary dictionaryWithObjectsAndKeys:[UIFont systemFontOfSize:sizefont],NSFontAttributeName,nil];
        CGSize  actualsize =[widget.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin  attributes:tdic context:nil].size;
        CGRect tmpRect = CGRectMake(rect.origin.x, rect.origin.y, actualsize.width, actualsize.height);
        return tmpRect;
    }else{
        CGSize strSize = [widget.text sizeWithFont:[UIFont systemFontOfSize:sizefont] constrainedToSize:size lineBreakMode:NSLineBreakByCharWrapping];
        CGRect tmpRect = CGRectMake(rect.origin.x, rect.origin.y, strSize.width, strSize.height);
        return tmpRect;
    }
}

-(NSString *)gen_uuid
{
    CFUUIDRef uuid_ref = CFUUIDCreate(NULL);
    CFStringRef uuid_string_ref= CFUUIDCreateString(NULL, uuid_ref);
    
    CFRelease(uuid_ref);
    NSString *uuid = [NSString stringWithString:(__bridge NSString*)uuid_string_ref];
    
    CFRelease(uuid_string_ref);
    return uuid;
}

+(void)moveToDBFile
{
    //1.获取数据库文件在工程中的路径--源路径
    NSString * sourcesPath = [[NSBundle mainBundle] pathForResource:@"SUPERVISION" ofType:@"db"];
    
    //2.获取沙盒中Document文件夹的路径--目的路径
    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString * documentPath = [paths objectAtIndex:0];
    NSString * desPath = [documentPath stringByAppendingPathComponent:@"SUPERVISION.db"];
    
    //3.通过NSFileManager类，将工程中的数据库文件复制到沙盒中。
    NSFileManager * fileManager  =[NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:desPath]){
        NSError * error;
        if ([fileManager copyItemAtPath:sourcesPath toPath:desPath error:&error]){
            DDLOG(@"数据库移动成功");
        }else{
            DDLOG(@"数据库移动失败");
        }
    }else{
        DDLOG(@"数据库已存在");
    }
}

+(NSString *)databaseFilePath
{
    NSArray *filePath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [filePath objectAtIndex:0];
    NSString *dbFilePath = [documentPath stringByAppendingPathComponent:@"SUPERVISION.db"];
    return dbFilePath;
    
}

+ (BOOL)isValidCoordinate:(CLLocationCoordinate2D)coordinate {
    if (CLLocationCoordinate2DIsValid(coordinate) &&
        (int)coordinate.latitude != 0 && (int)coordinate.longitude != 0) {
        return YES;
    }
    return NO;
}

//获取数据库指针

+(FMDatabase*)getDb{
    //paths： ios下Document路径，Document为ios中可读写的文件夹
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    //dbPath： 数据库路径，在Document中。
    NSString *dbPath = [documentDirectory stringByAppendingPathComponent:@"SUPERVISION.db"];
    //创建数据库实例 db  这里说明下:如果路径中不存在"Test.db"的文件,sqlite会自动创建"Test.db"
    FMDatabase * db= [FMDatabase databaseWithPath:dbPath] ;
    return db;
}

//获取文件大小
-(long long) fileSizeAtPath:(NSString*) filePath{
    NSFileManager* manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

//系统级的存储keychain

+ (NSMutableDictionary *)getKeychainQuery:(NSString *)service {
    return [NSMutableDictionary dictionaryWithObjectsAndKeys:
            (__bridge_transfer id)kSecClassGenericPassword,(__bridge_transfer id)kSecClass,
            service, (__bridge_transfer id)kSecAttrService,
            service, (__bridge_transfer id)kSecAttrAccount,
            (__bridge_transfer id)kSecAttrAccessibleAfterFirstUnlock,(__bridge_transfer id)kSecAttrAccessible,
            nil];
}
//保存
+ (void)save:(NSString *)service data:(id)data {
    //Get search dictionary
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Delete old item before add new item
    SecItemDelete((__bridge_retained CFDictionaryRef)keychainQuery);
    //Add new object to search dictionary(Attention:the data format)
    [keychainQuery setObject:[NSKeyedArchiver archivedDataWithRootObject:data] forKey:(__bridge_transfer id)kSecValueData];
    //Add item to keychain with the search dictionary
    SecItemAdd((__bridge_retained CFDictionaryRef)keychainQuery, NULL);
}
//取出
+ (id)load:(NSString *)service {
    id ret = nil;
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    //Configure the search setting
    [keychainQuery setObject:(id)kCFBooleanTrue forKey:(__bridge_transfer id)kSecReturnData];
    [keychainQuery setObject:(__bridge_transfer id)kSecMatchLimitOne forKey:(__bridge_transfer id)kSecMatchLimit];
    CFDataRef keyData = NULL;
    if (SecItemCopyMatching((__bridge_retained CFDictionaryRef)keychainQuery, (CFTypeRef *)&keyData) == noErr) {
        @try {
            ret = [NSKeyedUnarchiver unarchiveObjectWithData:(__bridge_transfer NSData *)keyData];
        } @catch (NSException *e) {
            NSLog(@"Unarchive of %@ failed: %@", service, e);
        } @finally {
        }
    }
    return ret;
}
//删除
+ (void)delete:(NSString *)service {
    NSMutableDictionary *keychainQuery = [self getKeychainQuery:service];
    SecItemDelete((__bridge_retained CFDictionaryRef)keychainQuery);
}

+(void)savePassWord:(NSString *)password
{
    NSMutableDictionary *usernamepasswordKVPairs = [NSMutableDictionary dictionary];
    [usernamepasswordKVPairs setObject:password forKey:KEY_UDID];
    [self save:KEY_IN_KEYCHAIN data:usernamepasswordKVPairs];
}

+(id)readPassWord
{
    NSMutableDictionary *usernamepasswordKVPair = (NSMutableDictionary *)[self load:KEY_IN_KEYCHAIN];
    return [usernamepasswordKVPair objectForKey:KEY_UDID];
}

+(void)deletePassWord
{
    [self delete:KEY_IN_KEYCHAIN];
}

//提示层

+ (void)showProgress:(UIView *) view
{
    [MBProgressHUD showHUDAddedTo:view animated:YES];
}

+ (void)showProgress:(UIView *) view showText:(NSString*)text
{
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
    hud.labelText = text;
}

+ (void) showTips:(NSString *)text toView:(UIView *)view
{
    MBProgressHUD * hud = [MBProgressHUD showHUDAddedTo:view animated:YES];
	// Configure for text only and offset down
	hud.mode = MBProgressHUDModeText;
	hud.labelText = text;
	[hud show:YES];
	[hud hide:YES afterDelay:1];
}

+ (void)showSuccessTips:(NSString *)text toView:(UIView *)view
{
    
}

+ (void)showErrorTips:(NSString *)text toView:(UIView *)view
{
    
}

+ (void)hideProgress:(UIView *)view
{
    [MBProgressHUD hideAllHUDsForView:view animated:YES];
}
//图片的压缩
+(UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize image:(UIImage *)image

{
    
    UIImage *sourceImage = image;
    
    UIImage *newImage = nil;
    
    CGSize imageSize = sourceImage.size;
    
    CGFloat width = imageSize.width;
    
    CGFloat height = imageSize.height;
    
    CGFloat targetWidth = targetSize.width;
    
    CGFloat targetHeight = targetSize.height;
    
    CGFloat scaleFactor = 0.0;
    
    CGFloat scaledWidth = targetWidth;
    
    CGFloat scaledHeight = targetHeight;
    
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
        
    {
        
        CGFloat widthFactor = targetWidth / width;
        
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            
            scaleFactor = widthFactor; // scale to fit height
        
        else
            
            scaleFactor = heightFactor; // scale to fit width
        
        scaledWidth= width * scaleFactor;
        
        scaledHeight = height * scaleFactor;
        
        // center the image
        
        if (widthFactor > heightFactor)
            
        {
            
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
            
        }
        
        else if (widthFactor < heightFactor)
            
        {
            
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            
        }
        
    }
    
    UIGraphicsBeginImageContext(targetSize); // this will crop
    
    CGRect thumbnailRect = CGRectZero;
    
    thumbnailRect.origin = thumbnailPoint;
    
    thumbnailRect.size.width= scaledWidth;
    
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil)
        
        NSLog(@"could not scale image");
    
    //pop the context to get back to the default
    
    UIGraphicsEndImageContext();
    
    return newImage;
    
}

//判断当前时间和过去时间的时间差
- (NSString *)intervalSinceNow:(NSString *) theDate
{
    if (!IS_NOT_EMPTY(theDate)){
        return @"时间格式错误";
    }
    if (theDate.length !=19){
        return @"时间格式错误";
    }
    NSDateFormatter *date=[[NSDateFormatter alloc] init];
    [date setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *d=[date dateFromString:theDate];
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    NSString *timeString=@"";
    
    NSTimeInterval cha=now-late;
    
    if (cha/3600<1) {
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        timeString = [timeString substringToIndex:timeString.length-7];
        if ([timeString intValue]==0){
            timeString = [NSString stringWithFormat:@"刚刚"];
        }else{
            timeString=[NSString stringWithFormat:@"%@分钟之前", timeString];
        }
    }else{
        NSString *nowTime = [NSString stringWithFormat:@"%@",
                             [date stringFromDate:[NSDate date]]];
        
        NSString * str1 = [theDate substringWithRange:NSMakeRange(8, 2)];
        NSString * str2 = [nowTime substringWithRange:NSMakeRange(8, 2)];
        if ([str2 compare:str1]==0){
            //今天
            timeString = [theDate substringWithRange:NSMakeRange(11, 5)];
        }else{
            NSString * strr1 = [theDate substringWithRange:NSMakeRange(0, 4)];
            NSString * strr2 = [theDate substringWithRange:NSMakeRange(0, 4)];
            if ([strr1 compare:strr2]==0){
                //今年
                timeString = [theDate substringWithRange:NSMakeRange(5, 11)];
            }else{
                //往年
                timeString = [theDate substringWithRange:NSMakeRange(0, 16)];
            }
        }
    }
    return timeString;
}

@end
